﻿using System.Linq;
using Microsoft.SharePoint;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;
using System;
using Trentacular.SharePoint.Deployment.Collections;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class SiteWebsLazyInitializer : BaseDomainListLazyInitializer<Site, Web>
    {
        protected override object InitializeTarget()
        {
            using (var spSite = new SPSite(Owner.Id))
            {
                try
                {
                    return spSite.AllWebs.Cast<SPWeb>()
                        .Select(w => CreateWeb(w))
                        .ToVirtualList();
                }
                catch (UnauthorizedAccessException)
                {
                    return new VirtualList<Web>();
                }
            }
        }

        private Web CreateWeb(SPWeb w)
        {
            using (w)
            {
                var web = new Web
                {
                    Id = w.ID,
                    Name = w.Name,
                    DisplayName = w.Title,
                    Site = Owner,
                    Url = w.Url
                };

                web.Features = Data.CreateProxiedList<WebFeature>(
                    new WebFeaturesLazyInitializer { Owner = web }
                    );

                return web;
            }
        }
    }
}
